package com.xiao.mall.foundation.entity;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.util.StringUtils;

/**
 * @author zhoushaofeng
 */
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public interface EnumValue {
    String NAME = "name";

    @JsonProperty("name")
    String name();

    @JsonProperty("desc")
    String getDesc();

    static <T extends Enum<T>> T create(Class<T> clazz, final JsonNode jsonNode) {
        if (jsonNode == null) {
            return null;
        }

        if (jsonNode.isObject()) {
            if (jsonNode.has(NAME) && StringUtils.hasLength(jsonNode.get(NAME).asText())) {
                return T.valueOf(clazz, jsonNode.get(NAME).asText());
            }

            return null;
        }

        if (StringUtils.hasLength(jsonNode.asText())) {
            return T.valueOf(clazz, jsonNode.asText());
        }

        return null;
    }
}
